<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row :gutter="40">
        <el-col :span="8">
          <el-button type="primary" @click="showAddCateDialog()">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 列表 -->
      <tree-table class="treeTable"
        show-index
        index-text='#'
        :expand-type='false'
        :selection-type='false'
        :data='cateList'
        :columns='columns'
        border>
        <!-- 是否有效 -->
        <template slot="isOk" slot-scope="scope">
            <i class="el-icon-success" style="color: green" v-if="scope.row.cat_deleted === false"></i>
            <i class="el-icon-error" style="color: green" v-else></i>
        </template>
        <template slot="order" slot-scope="scope">
            <el-tag size='mini'  v-if="scope.row.cat_level === 0">一级</el-tag>
            <el-tag size='mini' type='success' v-else-if="scope.row.cat_level === 1">二级</el-tag>
            <el-tag size='mini' type='danger' v-else>三级</el-tag>
        </template>
        <template slot="option" slot-scope="scope">
            <el-button size='mini' type="primary" @click='editCateDialog(scope.row.cat_id)'>编辑</el-button>
            <el-button size='mini' type="warning" @click='deleteCateDialog(scope.row.cat_id)'>删除</el-button>
        </template>
      </tree-table>
      <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="this.queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="this.total">
    </el-pagination>
    </el-card>
    <el-dialog
      @close='addCateDialogClose()'
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="30%">
      <el-form :model="addCateForm" :rules="addCateFormRules" ref="addCateFormRef" label-width="100px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!-- props是配置对象 -->
          <el-cascader
            clearable
            change-on-select
            expand-trigger= 'hover'
            v-model="selectedKeys"
            :options="parentCateList"
            :props= "cascaderProps"
            @change="cascaderCateChange"></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑分类 -->
    <el-dialog
      title="编辑分类"
      :visible.sync="editCateDialogVisible"
      width="30%">
      <el-form :model="editCateForm" :rules="editCateFormRules" ref="editCateFormRef" label-width="100px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      // 查询条件
      queryInfo: {
        type: 3,
        // 每页显示多少条数据
        pagesize: 5,
        // 当前页码
        pagenum: 1
      },
      // 商品分类数据列表
      cateList: [],
      total: 0,
      //   表格各列的配置
      columns: [{
        label: '分类名称',
        prop: 'cat_name'
      }, {
        label: '是否有效',
        type: 'template',
        template: 'isOk'
      }, {
        label: '排序',
        type: 'template',
        template: 'order'
      }, {
        label: '操作',
        // 定义为模板列
        type: 'template',
        // slot的名称
        template: 'option'
      }],
      //   添加分类对话框的显示隐藏
      addCateDialogVisible: false,
      // 添加分类的表单数据
      addCateForm: {
        // 分类名称
        cat_name: '',
        // 分类父 ID `0`表示一级分类；`1`表示二级分类；`2`表示三级分类
        cat_pid: 0,
        // 分类等级
        cat_level: 0
      },
      // 添加分类的校验规则
      addCateFormRules: {
        cat_name: [
          { required: true, message: '必填分类名', trigger: 'blur' }
        ]
      },
      parentCateList: [],
      // 级联选择器配置对象
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 选中的腹肌分类的id数组
      selectedKeys: [],
      editCateDialogVisible: false,
      editCateForm: {},
      editCateFormRules: {
        cat_name: [
          { required: true, message: '必填分类名', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    //   获取商品分类列表 并且保存数据
    async getCateList () {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error('获取商品分类列表失败')
      this.cateList = res.data.result
      this.total = res.data.total
    },
    // 监听pagesize改变
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getCateList()
    },
    // 监听pagenum 改变
    handleCurrentChange (newNum) {
      this.queryInfo.pagenum = newNum
      this.getCateList()
    },
    // 添加分类按钮
    showAddCateDialog () {
      this.addCateDialogVisible = true
      this.getParentCateList()
    },
    // 获取父级分类的数据列表 值：1，2，3 分别表示显示一层二层三层分类列表
    async getParentCateList () {
      const { data: res } = await this.$http.get('categories', { params: { type: 2 } })
      if (res.meta.status !== 200) return this.$message.error('商品分类数据列表获取失败')
      this.parentCateList = res.data
      console.log(this.parentCateList)
    },
    // cascader级联 选中项变化触发
    cascaderCateChange () {
      if (this.selectedKeys.length > 0) {
        //   选中了父级分类
        this.addCateForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
        this.addCateForm.cat_level = this.selectedKeys.length
        return
      } else {
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
      }
      console.log(this.selectedKeys)
    },
    // 添加分类的确定按钮
    addCate () {
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('categories', this.addCateForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加失败')
        }
        this.$message.success('添加成功')
        this.addCateDialogVisible = false
        this.getCateList()
      })
      console.log(this.addCateForm)
    },
    // 添加分类对话框关闭
    addCateDialogClose () {
      this.$refs.addCateFormRef.resetFields()
      this.selectedKeys = []
      this.addCateForm.cat_level = 0
      this.addCateForm.cat_pid = 0
    },
    // 删除分类对话框
    deleteCateDialog (id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete('categories/' + id)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        this.getCateList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 编辑分类对话框
    async editCateDialog (id) {
      this.editCateDialogVisible = true
      const { data: res } = await this.$http.get('categories/' + id)
      if (res.meta.status !== 200) return this.$message.error('编辑失败')
      this.editCateForm = res.data
      console.log(this.editCateForm)
    },
    // 编辑分类确定按钮
    editCate () {
      this.$refs.editCateFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.editCateForm.cat_id}`, { cat_name: this.editCateForm.cat_name })
        if (res.meta.status !== 200) return this.$message.error('编辑提交失败')
        this.$message.success('编辑提交成功')
        this.editCateDialogVisible = false
        this.getCateList()
      })
    }
  }
}
</script>
<style lang="less" scoped>
.treeTable {
    margin-top: 10px;
    margin-bottom: 10px;
}
.el-cascader {
    width: 100%;
}
</style>
